<template>
	<view class="login">
		<image class="top-bg" mode="widthFix" src="/static/loginbg.png"></image>
		<view class="pl-3 pr-3 login-wrap">
			<view class="flex justify-center mb-2">
				<u-tabs :current="currTab" :list="menuList" lineWidth="30" lineHeight="2" lineColor="#fff"
					:activeStyle="activeStyle" :inactiveStyle="inactiveStyle" @click="handleMenuChange"></u-tabs>
			</view>
			<view class="pt-1 pb-2 pl-3 pr-3 login-panel" v-show="currTab == 0">
				<u--form class="mb-3 login-form" :rules="loginRules" ref="loginFormRef" labelPosition="top"
					:borderBottom="false" :model="loginForm">
					<u-form-item label="账号" prop="acc" :borderBottom="false">
						<u--input v-model="loginForm.acc" placeholder="通行证ID/手机号码/邮箱" border="none"
							:customStyle="inputStyle" clearable></u--input>
					</u-form-item>
					<u-form-item label="密码" prop="pwd" :borderBottom="false">
						<u--input password v-model="loginForm.pwd" placeholder="请输入密码" border="none"
							:customStyle="inputStyle" clearable>
						</u--input>
					</u-form-item>
				</u--form>
				<u-button @click="handleLogin" color="#007aff" text="登录" size="" shape="circle"></u-button>
				<view class="flex justify-end mt-3 mb-1">
					<navigator url="/pages/login/forgotPassword/forgotPassword">
						<view class="forgot">忘记密码？</view>

					</navigator>
				</view>
			</view>
			<view class="pt-1 pb-2 pl-3 pr-3 login-panel" v-show="currTab == 1">
				<u--form class="mb-3 login-form" labelWidth="60" labelPosition="top" :borderBottom="false"
					:model="registerForm" :rules="registerRules" ref="registerFormRef">
					<u-form-item label="手机号" prop="Tel" :borderBottom="false">
						<u--input v-model="registerForm.Tel" placeholder="请输入手机号" border="none" :customStyle="inputStyle"
							clearable></u--input>
					</u-form-item>
					<u-form-item label="验证码" prop="VerifyCode" :borderBottom="false">
						<u--input v-model="registerForm.VerifyCode" placeholder="请输入验证码" border="none"
							:customStyle="inputStyle" clearable>
							<template slot="suffix">
								<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒后重新获取"></u-code>
								<u-button class color="#007aff" @tap="getCode" :text="tips" type="success" size="mini">
								</u-button>
							</template>
						</u--input>
					</u-form-item>
					<u-form-item label="密码" prop="Pwd" :borderBottom="false">
						<u--input password v-model="registerForm.Pwd" placeholder="请输入6-20位的密码" border="none"
							:customStyle="inputStyle" clearable>
						</u--input>
					</u-form-item>
					<u-form-item label="确认密码" prop="Pwd1" :borderBottom="false">
						<u--input password v-model="registerForm.Pwd1" placeholder="请确认密码" border="none"
							:customStyle="inputStyle" clearable>
						</u--input>
					</u-form-item>
					<u-form-item label="昵称" prop="DispName" :borderBottom="false">
						<u--input v-model="registerForm.DispName" placeholder="请输入昵称" border="none"
							:customStyle="inputStyle" clearable></u--input>
					</u-form-item>
				</u--form>
				<u-button @click="handleRegister" color="#007aff" text="注册" size="" shape="circle"></u-button>
				<view class="flex justify-center mt-3 mb-1">
					<view class="forgot" @click="currTab = 0">已有账号，去注册</view>
				</view>
			</view>
		</view>
		<u-popup :show="showCmpy" mode="center" :round="5">
			<view class="order-popup">
				<view class="popup-title">选择公司</view>
				<u-radio-group v-model="currCmpy" :borderBottom="true" placement="column" iconPlacement="right"
					activeColor="#007aff" inactiveColor="#fff">
					<u-list height="200">
						<u-list-item v-for="(item, index) in cmpyList" :key="index">
							<u-radio :customStyle="{ marginBottom: '16px' }" :label="item.CmpyName" :name="index">
							</u-radio>
						</u-list-item>
					</u-list>
				</u-radio-group>

				<view class="btns">
					<view class="ml-3 f-1">
						<u-button @click="handleCmpyDone" color="#007aff" shape="circle" text="确定"></u-button>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import {
	authorizeByPwd,
	accessToken,
	fetchUserInfo,
	fetchCompanyList,
	loginCompany,
	regByValidCode
} from "@/apis/user.js";
import {
	getZoneInfo,
	sendVerifyCode
} from "@/apis/common.js";


export default {
	data() {
		return {
			currTab: 0,
			currCmpy: '',
			showCmpy: false,
			cmpyList: [],
			menuList: [{
				name: '登录'
			},
			{
				name: '注册'
			},
			],
			activeStyle: {
				color: '#fff',
				transform: 'scale(1.05)'
			},
			inactiveStyle: {
				color: '#fff',
				transform: 'scale(1)'
			},
			inputStyle: {
				background: '#f1f1f1',
				padding: '6px 8px'
			},
			loginForm: {
				acc: '',
				pwd: '',
				response_type: 'code',
				scope: 'base',
				state: '1234'
			},
			loginRules: {
				acc: {
					required: true,
					message: '请输入账号',
					trigger: ['blur', 'change']
				},
				pwd: {
					min: 6,
					max: 20,
					required: true,
					message: '请输入6-20位的密码',
					trigger: ['blur', 'change']
				},
			},
			registerForm: {
				Tel: '',
				Pwd: '',
				Pwd1: '',
				SmsId: '',
				VerifyCode: '',
				DispName: '',
				TGID: '0',
			},
			registerRules: {
				Tel: [{
					required: true,
					message: '请输入手机号',
					trigger: ['change', 'blur'],
				},
				{
					validator: (rule, value, callback) => {
						return uni.$u.test.mobile(value);
					},
					message: '手机号码不正确',
					trigger: ['change', 'blur'],
				}
				],
				Pwd: {
					min: 6,
					max: 20,
					required: true,
					message: '请输入6-20位的密码',
					trigger: ['blur', 'change']
				},
				Pwd1: [{
					required: true,
					message: '请输入密码',
					trigger: ['change', 'blur'],
				},
				{
					validator: (rule, value, callback) => {
						return value == this.registerForm.Pwd;
					},
					message: '两次输入密码不一致',
					trigger: ['change', 'blur'],
				}
				],
				VerifyCode: {
					min: 4,
					required: true,
					message: '请输入正确的验证码',
					trigger: ['change', 'blur'],
				},
				DispName: {
					required: true,
					message: '昵称',
					trigger: ['change', 'blur'],
				},

			},
			tips: ''
		};
	},
	methods: {
		async handleLogin() {
			if (!await this.$refs.loginFormRef.validate()) return;

			const loginData = this.loginForm
			const params = {
				response_type: loginData.response_type,
				scope: loginData.scope,
				state: loginData.state,
			}
			const data = {
				acc: loginData.acc,
				pwd: loginData.pwd,
			}
			const accountInfo = {}
			let loginRes = await authorizeByPwd(params, data)
			if (loginRes.MsgCode != 0) return
			accountInfo.accountId = loginRes.AccountId
			accountInfo.code = loginRes.code
			accountInfo.sessionId = loginRes.sessionid
			accountInfo.state = loginRes.state

			let atRes = await accessToken({
				code: accountInfo.code,
				grant_type: 'authorization_code'
			})
			if (atRes.MsgCode != 0) return
			accountInfo.accessToken = atRes.access_token
			accountInfo.refreshToken = atRes.refresh_token

			uni.setStorageSync('accountInfo', accountInfo);
			// 先存一次，不然下面的请求在api里拿不到accessToken

			let userInfoRes = await fetchUserInfo({
				AccountId: accountInfo.accountId,
				lang: 'zh_CN'
			})
			if (userInfoRes.MsgCode != 0) return
			accountInfo.userInfo = userInfoRes

			let cmpylRes = await fetchCompanyList({
				AccountId: accountInfo.accountId,
				SysId: '6666'
			})
			if (cmpylRes.MsgCode != 0) return
			accountInfo.cmpyList = cmpylRes.data.CmpyList
			this.cmpyList = cmpylRes.data.CmpyList
			this.showCmpy = true
			uni.setStorageSync('accountInfo', accountInfo);


			const zRes = await getZoneInfo()
			if (zRes.MsgCode == 0) {
				const provinces = []
				const zoneInfo = zRes.data.map(item => {
					provinces.push(item.name)
					item.cityList = item.citys.map(cItem => {
						cItem.townList = cItem.towns.map(tItem => {
							return tItem.name
						})
						return cItem.name
					})
					return item
				})
				uni.setStorageSync('zoneInfo', zoneInfo);
				uni.setStorageSync('provinces', provinces);
			}

		},
		async handleCmpyDone() {
			const CmpyCatgMap = {
				0: 'Normal',
				1: 'QCJY',
				2: 'SJWX',
				3: 'JD',
				4: 'DNWX',
				5: 'JDWX',
				6: 'JZBJ',
				7: 'CDZ',
				8: 'School',
				101: 'GZYWDC'
			}
			console.log('handleCmpyDone',this.currCmpy)
			const accountInfo = uni.getStorageSync('accountInfo')
			accountInfo.currCmpy = this.cmpyList[this.currCmpy]

			let lCmpyRes = await loginCompany({
				AccountId: accountInfo.accountId,
				CmpyCode: accountInfo.currCmpy.CmpyCode,
				SysId: '6666',
				Platform: 'android'
			})
			if (lCmpyRes.MsgCode != 0) return
			accountInfo.loginCompany = lCmpyRes.data
			console.log('lCmpyRes res', lCmpyRes, accountInfo)

			uni.setStorageSync('routeType', CmpyCatgMap[accountInfo.loginCompany.CmpyCatg]);
			uni.setStorageSync('accountInfo', accountInfo);
			uni.switchTab({
				url: '/pages/workOrder/workOrder'
			})
		},
		codeChange(text) {
			this.tips = text;
		},
		async handleRegister() {
			if (!await this.$refs.registerFormRef.validate()) return;

			const registerData = this.registerForm
			const res = await regByValidCode(registerData)
			console.log('?', res)
			if (res.MsgCode == 0) {
				uni.showToast({
					title: '注册成功！请登录',
					duration: 2000,
					icon: 'none'
				});
				this.currTab = 0
				this.registerForm = {
					Tel: '',
					Pwd: '',
					Pwd1: '',
					SmsId: '',
					VerifyCode: '',
					DispName: '',
					TGID: '0',
				}
			}
		},

		async getCode() {
			if (!this.registerForm.Tel) {
				return uni.showToast({
					title: '请输入手机号',
					duration: 1000,
					icon: 'none'
				});
			} else if (this.$refs.uCode.canGetCode) {
				uni.showLoading({
					title: '正在获取验证码'
				})
				const res = await sendVerifyCode({
					OrderCmpyCode: '',
					Tel: this.registerForm.Tel
				})

				if (res.MsgCode == 0 && res.data.SmsId) {
					this.registerForm.SmsId = res.data.SmsId
					uni.$u.toast('验证码已发送');
					this.$refs.uCode.start();
					console.log('this.registerForm', this.registerForm)
				}

			} else {
				uni.$u.toast('倒计时结束后再发送');
			}
		},
		handleMenuChange(item) {
			this.currTab = item.index
		},
	}
}
</script>

<style lang="scss">
.login {
	.top-bg {
		width: 100%;
		margin-top: -44px;
		z-index: -1;
	}

	.login-wrap {
		margin-top: -1240rpx;

		.login-panel {
			background-color: #fff;
			border-radius: $s-border-radius;
			box-shadow: $s-bg-shadow;

			.forgot {
				color: #acacac;
				font-size: 20rpx;
			}
		}
	}
}

.order-popup {
	width: 600rpx;
	padding: 25rpx 30rpx;

	.popup-title {
		color: #333;
		font-weight: bold;
		font-size: 28rpx;
		margin-bottom: 30rpx;
	}

	::v-deep .uni-input-wrapper {
		.uni-input-input {
			text-align: left;
		}

		.input-placeholder {
			text-align: left;
			color: #808080;
		}
	}

	.popup-tip {
		margin-top: 20rpx;
		color: #555;
		font-size: 22rpx;
	}

	.btns {
		display: flex;
		justify-content: center;
		width: 100%;
		padding: 20rpx 0;
		margin-top: 30rpx;
		background-color: #fff;

		::v-deep .u-button {
			margin: 0;
		}
	}

	.order-radio {
		padding: 20rpx;
		margin-top: 30rpx;
		// ::v-deep .uicon-checkbox-mark{
		// 	color:#F65D30 !important;
		// }
	}
}
</style>
